
$(function(){


window.AppView = Backbone.View.extend({
	el: $("#profile-page"),
	events: {
		"click .create-list-link"		: "createNewList",
	},
	
	initialize: function(options) {
		_.bindAll(this, "onOpenList", "createNewList", "onSaveList", "onDeleteList");
		
		this.listBuilderView = new ListBuilderView();
		$("#title-input").val("");
		
		if (options.username !== undefined && options.username !== null)
		{
			// fetch user's lists, but lazily populate items
			this.myListCollectionView = new MyListCollectionView({ "username": options.username });
			this.myListCollectionView.addOnOpenListListener(this.onOpenList);
			this.myListCollectionView.addOnDeleteListListener(this.onDeleteList);
		}
	},
	
	onDeleteList: function(list) {
		if (this.listBuilderView.list === list) {
			$("#list-builder").html("");
		}
	},
	
	onOpenList: function(list) {
		//$(this.listBuilderView.el).html("");
		//list.items.refresh(list.items);
		//$(this.listBuilderView.el).remove();
		
		if (this.listBuilderView.list !== undefined) {
			this.listBuilderView.list.items.unbind();
			this.listBuilderView.list.items.each(function (item) {
				if (item !== undefined) {
					item.unbind();
				};
			});
			this.listBuilderView.titleInput.unbind();
			this.listBuilderView.titleInput.val("");
		}
		
		// destroy previous plupload instance
		if (this.listBuilderView.uploader !== undefined) {
			this.listBuilderView.uploader.destroy();
		}

		this.activeList = list;
		this.listBuilderView = new ListBuilderView({ "list" : list });
		//this.listBuilderView.list.fetch();
	},
	
	createNewList: function(e) {
		e.preventDefault();
		
		// clear html of previously active list
		this.$("#item-list").html("");
		
		
		if (this.listBuilderView.list !== undefined) {
			// unbind all the previously active view events
			this.listBuilderView.list.items.unbind();
			this.listBuilderView.list.items.each(function (item) {
				if (item !== undefined) {
					item.unbind();
				};
			});
			this.listBuilderView.titleInput.unbind();
			
			// clear title input val
			this.listBuilderView.titleInput.val("");
		}
		
		// destroy previous plupload instance
		if (this.listBuilderView.uploader !== undefined) {
			this.listBuilderView.uploader.destroy();
		}
		
		var newList = new List;
		this.activeList = newList;
		var that = this;			
		newList.save(
			{ done: "false" }, 
			{ success: this.onSaveList,
				error: function (model, response) {}
		});
	},

	onSaveList: function(model, response) {
		var id = model.get("id");
		this.activeList.set({"id": id});
		this.activeList.updateUrls();
		this.activeList.items.url = "/api/list/" + id + "/items/";
		
		// add new list to myListCollectionView
		this.myListCollectionView.add(this.activeList);
		
		// create new list and pass it to listbuilder
		this.listBuilderView = new ListBuilderView({ "list" : this.activeList });
	}
})
})